<script setup lang="ts">
import { OIcon, OPopover, useMessage } from '@opensig/opendesign';
import IconShare2 from '~icons/app/icon-share2.svg';
import IconDownload from '~icons/app/icon-download.svg';
import IconCollect from '~icons/app/icon-collect.svg';
import IconCollected from '~icons/app/icon-collected.svg';

import { useScreen } from '@/composables/useScreen.ts';
import { computed, onMounted, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import showMsg from '@/utils/showMsg.ts';
import { useCommonStore } from '@/stores/common.ts';
import { useRoute } from 'vitepress';
import { useUserInfoStore } from '@/stores/user.ts';
import { addCollectApi, getCollectStatusApi, removeCollectApi } from '@/api/api-collect.ts';
import { useMenuStore } from '@/stores/menu.ts';
import { t } from '@/i18n';

const props = defineProps<{
  title?: string;
}>();
const userInfoStore = useUserInfoStore();
const commonStore = useCommonStore();
const { isPhone } = useScreen();
const { userId } = storeToRefs(userInfoStore);
// -------------------- 下载html --------------------
const downloadDoc2 = async () => {
  // 获取所有外部样式表
  const stylesheets = Array.from(document.styleSheets);
  // 创建页面副本
  const clone = document.documentElement.cloneNode(true);
  // 处理样式表
  const stylePromises = stylesheets.map(async (stylesheet) => {
    try {
      if (stylesheet.href) {
        const response = await fetch(stylesheet.href);
        const css = await response.text();
        const style = document.createElement('style');
        style.textContent = css;
        return style;
      }
    } catch (error) {
      console.warn('无法加载样式表:', stylesheet.href, error);
      return null;
    }
  });

  // 等待所有资源加载完成
  const loadedStyles = (await Promise.all(stylePromises)).filter((style) => style);
  // 移除原有的外部资源引用
  clone.querySelectorAll('link[rel="stylesheet"]').forEach((link) => link.remove());
  clone.querySelectorAll('script[src]').forEach((script) => script.remove());

  // 移除不需要的dom
  clone.querySelector('.app-header').remove();
  clone.querySelector('.layout-doc-aside').remove();
  clone.querySelector('.aside-mask').remove();
  clone.querySelector('.breadcrumb').remove();
  clone.querySelector('.doc-header-right').remove();
  clone.querySelector('.doc-footer').remove();
  clone.querySelector('.doc-anchor').remove();
  clone.querySelector('.floating-btn-layout').remove();
  clone.querySelector('.o-scrollbar').remove();
  clone.querySelector('.sub-header')?.remove();

  // 添加内联的样式和脚本
  const head = clone.querySelector('head');
  loadedStyles.forEach((style) => head.appendChild(style));

  // 覆盖样式
  const bgContentEle = document.querySelector('.markdown-content');
  const bgStyleEle = window.getComputedStyle(bgContentEle);
  const style = document.createElement('style');
  style.setAttribute('type', 'text/css');
  style.textContent = `
  .layout-doc {
    padding-top: 0 !important;
  }
  .layout-doc-content {
    margin: 0 auto !important;
    padding: 0 !important;
  }
  .layout-main {
    padding: ${isPhone.value ? 24 : 32}px !important;
    width: 100vw !important;
  }
  .layout-doc-content {
    width: 100% !important;
    max-width: 1200px !important;
  }
  .markdown-content {
    background-image: ${bgStyleEle.backgroundImage} !important;
  }
  button.copy, .o-popup, .el-popper, o-scrollbar {
    display: none !important;
  }
  .floating-btn-layout {
    display: none !important;
  }
  `;
  head.appendChild(style);

  const script = document.createElement('script');
  script.textContent = `
  const btns = document.querySelectorAll('.copy-btn');
  [...btns].forEach(btn => {
    btn.addEventListener('click', () => {
      navigator.clipboard.writeText(btn?.parentElement?.innerText);
    });
  });
  `;
  const body = clone.querySelector('body');
  body.appendChild(script);

  // 处理img

  const imgs = clone.querySelectorAll('img');
  imgs.forEach((img) => {
    img.src = img.src;
  });

  // 处理a标签
  const links = clone.querySelectorAll('a');
  links.forEach((a) => {
    if (!a.href.startsWith(location.href)) {
      a.href = a.href;
    }
  });

  // 处理link icon 标签
  const link = clone.querySelector('link[rel="icon"]');
  if (link) {
    link.href = link.href;
  }

  // 创建下载链接
  const html = clone.outerHTML;
  const blob = new Blob([html], { type: 'text/html' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `${props.title || 'saved-page'}.html`;

  // 触发下载
  document.body.appendChild(a);
  a.click();

  // 清理
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  message.success({
    content: '下载成功',
  });
};

// -------------------- 分享 --------------------
const message = useMessage();
const share = () => {
  navigator.clipboard.writeText(location.href);
  if (isPhone.value) {
    showMsg('复制成功');
  } else {
    message.success({
      content: '复制成功',
    });
  }
};

// -------------------- 收藏 --------------------
const route = useRoute();
const isCollected = ref(false); // 是否收藏
const menuStore = useMenuStore();
const { breadCrumbParams } = storeToRefs(menuStore);
const handlePath = (path: string) => {
  if (path.startsWith('/')) {
    path = path.slice(1);
  }
  if (path.includes('.html')) {
    return path.slice(0, -5);
  }
  return path;
};
const collectText = computed(() => (isCollected.value ? '取消收藏' : '收藏文档'));
const getCollectStatus = async () => {
  if (!userId.value) {
    isCollected.value = false;
  } else {
    const res = await getCollectStatusApi({ path: handlePath(route.path), doc_type: 0 });
    isCollected.value = res?.data?.data || false;
  }
};
const toggleDocCollect = async () => {
  if (!userId.value) {
    commonStore.setLoginDialogVisible(true);
  } else {
    const path = [t('docs.documentCenter'), ...breadCrumbParams.value.map((item) => item.label)].join('/');
    if (!isCollected.value) {
      await addCollectApi({ path: handlePath(route.path), article_path: path, doc_type: 0 });
      message.success({
        content: '收藏成功',
      });
    } else {
      await removeCollectApi({ path: handlePath(route.path), doc_type: 0 });
      message.success({
        content: '已取消收藏',
      });
    }
    isCollected.value = !isCollected.value;
  }
};

onMounted(() => {
  getCollectStatus();
});
watch([() => userId.value, () => route.path], () => {
  isCollected.value = false;
  getCollectStatus();
});
</script>

<template>
  <div class="doc-tools">
    <OPopover trigger="hover">
      <template #target>
        <OIcon v-analytics.addUrl="{ service: 'docs', properties: { target: '下载文档', type: 'button' } }" @click="downloadDoc2" class="">
          <IconDownload />
        </OIcon>
      </template>
      下载文档
    </OPopover>
    <OPopover trigger="hover">
      <template #target>
        <OIcon v-analytics.addUrl="{ service: 'docs', properties: { target: collectText, type: 'button' } }" @click="toggleDocCollect" class="">
          <IconCollect v-if="!isCollected" />
          <IconCollected v-else />
        </OIcon>
      </template>
      {{ collectText }}
    </OPopover>
    <OPopover trigger="hover">
      <template #target>
        <OIcon v-analytics.addUrl="{ service: 'docs', properties: { target: '复制链接', type: 'button' } }" @click="share">
          <IconShare2 />
        </OIcon>
      </template>
      复制链接
    </OPopover>
  </div>
</template>

<style scoped lang="scss">
.doc-tools {
  display: flex;
  column-gap: 16px;
  align-items: center;
  .o-icon {
    font-size: 24px;
    cursor: pointer;
    height: 24px;
    color: var(--o-color-info2);
    @include hover {
      color: var(--o-color-ubmc);
    }
  }
}
</style>
